package demo1;

import java.util.InputMismatchException;
import java.util.Scanner;

public class Test {
    //处理异常
    public static void main1(String[] args) {
        try{
            System.out.println(10/0);
        }catch(ArithmeticException e){
            e.printStackTrace(); //可以快速定位异常出现的位置
            System.out.println("出现算数异常");
        }
        System.out.println("继续执行后续代码");
    }
    public static void main2(String[] args) {
        try {
            int[] array = {1, 2, 3, 4};
            //array=null;
            System.out.println(array[0]);
        }catch(NullPointerException e){
            e.printStackTrace();
            System.out.println("出现空指针异常");
        }catch(ArrayIndexOutOfBoundsException e){
            e.printStackTrace();
            System.out.println("数组越界异常");
        }
        System.out.println("继续执行后续代码");
     }
    //异常的抛出
    public static void main3(String[] args) {
        try {
            int[] array = {1, 2, 3, 4};
            array=null;
            System.out.println(10/0);
            System.out.println(array[0]);
        }catch(NullPointerException e){
            e.printStackTrace();
            System.out.println("出现空指针异常");
        }catch(ArrayIndexOutOfBoundsException e){
            e.printStackTrace();
            System.out.println("数组越界异常");
        }catch(Exception e){
            System.out.println("未知异常");
        }
        System.out.println("继续执行后续代码");
    }
    //主动用throw抛出异常
    public static void test1(int a){
        try{
            if(a == 10){
                throw new CloneNotSupportedException(); //受查异常，必须此时处理
            }
        }catch(CloneNotSupportedException e){
            e.printStackTrace();
        }
    }
    //此时不算处理异常 ，因为会交给JVM
    public static void test12(int a) throws CloneNotSupportedException {
        if(a == 10){
            throw new CloneNotSupportedException(); //受查异常，必须此时处理
        }
    }
    public static void main4(String[] args) {
        test1(10);

        System.out.println("继续执行代码");
    }
    //finally -- 用来解决因为异常而导致有些代码无法执行的问题
    public static void main5(String[] args) {
        try (Scanner scanner = new Scanner(System.in)) {
            int n = scanner.nextInt();

        } catch (InputMismatchException e) {
            e.printStackTrace();
            System.out.println("输入的数据不匹配");
        } finally {
            //不论是否抛出都会执行，一般用来关闭资源
            System.out.println("执行了finally部分");
        }
    }
    //自定义异常类
    public static void main(String[] args) {
        System.out.println("我太难了");
    }
}
